#include "qtcp_client.h"
#include <QHostAddress>

TCPClient::TCPClient(QObject *parent) : QObject(parent)
{
    m_socket = new QTcpSocket(this);
    connect(m_socket, &QTcpSocket::connected, this, &TCPClient::onConnected);
    connect(m_socket, &QTcpSocket::disconnected, this, &TCPClient::onDisconnected);
    connect(m_socket, &QTcpSocket::readyRead, this, &TCPClient::onReadyRead);
    connect(m_socket, &QTcpSocket::bytesWritten, this, &TCPClient::bytesWritten);
    connect(m_socket, &QTcpSocket::errorOccurred, this, &TCPClient::onError);
}

void TCPClient::connectToServer(const QString &host, quint16 port)
{
    if (m_socket->state() != QAbstractSocket::UnconnectedState)
        return;
    m_socket->connectToHost(QHostAddress(host), port);
}

void TCPClient::disconnectFromServer()
{
    if (m_socket->state() != QAbstractSocket::UnconnectedState)
        m_socket->disconnectFromHost();
}

void TCPClient::sendMessage(const QByteArray &data)
{
    if (m_socket->state() == QAbstractSocket::ConnectedState)
        m_socket->write(data);
}

void TCPClient::onConnected()
{
    emit connected();
}
void TCPClient::onDisconnected()
{
    emit disconnected();
}

void TCPClient::onReadyRead()
{
    QByteArray buf = m_socket->readAll();
    if (!buf.isEmpty())
        emit messageReceived(buf);
}

void TCPClient::onError(QAbstractSocket::SocketError)
{
    emit errorOccurred(m_socket->errorString());
}